function waitSpan(txt) {
   return '<span id="formerrors" class="loginWaitMessage" ' +
       'style="margin: -25px 0px 0px 0px; *margin-top:-45px;">' +
       '<img src="/ocie/images/icons/hourglass.gif" alt="" />' + txt +
       '</span>';
}


function simpleSpan(txt) {
    return '<span id="formerrors" class="loginWaitMessage" ' +
        'style="position:absolute; float:left; width:200px; margin-top:-615px; *margin-top:-650px; _margin-top:-665px;">' + txt +
	'</span>';
}


function errorSpan(txt) {
    return '<span id="formerrors" class="loginGeneralErrorMessage" ' +
        'style="margin: -25px 0px 0px 0px; *margin-top:-45px;">' +
        '<img src="/ocie/images/icons/error.gif" alt="" />' + txt +
        '</span>';
}


function setMessage(msg) {
    $("#formerrors").remove();
    $("#form1").parent().append(msg);
}


function loginSuccess() {
    setMessage(waitSpan('Login successful.  Redirecting.'));
    window.location = "/ocie/schedule/";
}


function loginError(req, status, exc) {
    switch (req.status) {
    case 400:
        setMessage(errorSpan('Login failed. Please try again.'));
        break
    default:
        setMessage(errorSpan('Server error. Please try again.'));
    }
}


function loginLinkClicked() {
    var msg = waitSpan('New login started...');
    setMessage(msg);
    var user = $("#username").val();
    var passwd = $("#password").val();
    jQuery.ajax({
        url:"/api/login/",
        type:"POST",
        data:{"username":user, "password":passwd}, 
        success:loginSuccess, 
        error:loginError
	});
    return false;
}


function loginFormKeyed(event) {
    if (event.which == 13) {
        loginLinkClicked();
    }
}


$(document).ready( function(){
    $("a.loginButton").attr("href", "");
    $("a.loginButton").click(loginLinkClicked);
    $("#form1").keydown(loginFormKeyed)
    var user = $.cookie("auth_user")
    if (user) {
        var msg = simpleSpan("You're logged out.  Please close your browser to clear your credentials.");
        setMessage(msg);
        setTimeout(function(){$("#formerrors").fadeOut()}, 10000);
        $("#form1 #username").val(user);
	$("#form1 #password").focus();
    } else {
	$("#form1 #username").focus();
    }
});
